<?php
/**
 *
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/5/15
 * Time: 11:44
 * 商户上传商品后台
 *
 */

namespace Admin\Controller;
use Think\Controller;

class BusinessController extends Controller{

    private $sellerGoods='';
    private $seller='';
    private $sellerID='';
    private $sellerGoodsGallery='';
    private $commonController='';
    private $orderInfo='';
    private $sellerDB='';
    private $orderGoods='';
    private $goods="";

    function __construct()
    {
        parent::__construct();
        $this->seller=session("seller");
        $this->sellerID=session("sellerID");
        if(empty($this->seller)||empty($this->sellerID))    // 如果商户登录后的SESSION 存在
        {
            $this->redirect("Login/sellerLogin");
        }
        $this->assign("seller",$this->seller);
        $this->assign("sellerID",$this->sellerID);
        $this->sellerGoods=D("Goods");    // 实例化对应的模型层
        $this->sellerGoodsGallery=D("Goods_gallery");
        $this->orderInfo=D('Order_info');
        $this->sellerDB=D("Seller");
        $this->orderGoods=D("Order_goods");
        $this->goods=D("Goods");
        $this->goods->startTrans();
//        $this->commonController=D('commonController');
        Layout("sellerAdmin");
    }

    public static function check_wap(){
        // 先检查是否为wap代理，准确度高
        if(stristr($_SERVER['HTTP_VIA'],"wap")){
            return true;
        }
        // 检查浏览器是否接受 WML.
        elseif(strpos(strtoupper($_SERVER['HTTP_ACCEPT']),"VND.WAP.WML") > 0){
            return true;
        }
        //检查USER_AGENT
        elseif(preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])){
            return true;
        }
        else{
            return false;
        }
    }

    /*
     * 商户产品的列表
     * 列表中的信息通过session中的商户ID 进行筛选， 每个用户只能看到自己的商品列表
     * */
    function index()
    {
        $allGoods=$this->sellerGoods->where("seller_id=".$this->sellerID)->select();
        foreach($allGoods as $key=>$r)
        {
            $allGoods[$key]['addTime_b']=date("Y-m-d H:i:s",$r['add_time']);
        }

        $this->assign("data",$allGoods);
        $this->display();
    }

    /*
     * 卖家ID
     * */
    function addGoods()
    {
        if($_POST)
        {
            $data=$_POST;
            $data['id']='';
            $data['seller_id']=$this->sellerID;

            //  缩略图的上传
            if(!empty($_FILES['thumb']['name']))
            {
                $data['thumb'] = $this->uploadOneImg("thumb",$_POST['goods_sn']);    // 上传缩略图
            }

            // 图上传end

            $data['last_update']=time();     //  最后一次修改的时间
            $data['add_time']=time();        //   添加的时间

            $aa=$this->sellerGoods->data($data)->add();
            if(isset($aa))
            {
                $this->sellerGoods->commit();
                $this->success("商品上传成功");
            }else{
                $this->sellerGoods->rollback();
                $this->error("商品上传失败");
            }
        }else{
            $this->display();
        }
    }

    /*
     * 商品修改
     * */
    function updataGoods($id='')
    {
        if($_POST)
        {
            $data=$_POST;
            if($data['is_promote']==1)     // 当 is_promote=1 时，表示开启促销 ，再去修改时间格式
            {
                $promote_start_date=$_POST['promote_start_date'];
                $yanG1=explode("-",$promote_start_date);
                $yanGstart=mktime(0,0,0,$yanG1[0],$yanG1[1],$yanG1[2]);      // 得到促销开始的时间戳

                $promote_end_date=$_POST['promote_end_date'];
                $yanG2=explode("-",$promote_end_date);
                $yanGend=mktime(0,0,0,$yanG2[0],$yanG2[1],$yanG2[2]);      // 得到促销结束的时间戳

                if($yanGstart>=$yanGend||empty($yanGstart)||empty($yanGend))
                {
                    $this->error("促销时间设置有问题!!!");

                }else{
                    $data['promote_start_date']=$yanGstart;
                    $data['promote_end_date']=$yanGend;
                }
            }      //促销部处理完成

            //  缩略图的上传
            if(!empty($_FILES['thumb']['name']))
            {
                $data['thumb'] = $this->uploadOneImg("thumb",$_POST['goods_sn']);    // 上传缩略图
            }

            if(!empty($_FILES['img']['name']))
            {
                $data['img']=$this->uploadOneImg("img",$_POST['goods_sn']);     // 上传图片
            }
            // 图上传end

            $data['last_update']=time();     //  最后一次修改的时间
            $data['add_time']=time();        //   添加的时间

            $aa=$this->sellerGoods->where('id='.$id)->save($data);
            if(isset($aa))
            {
                $this->sellerGoods->startTrans();
                $this->success("商品修改成功");
            }else{
                $this->sellerGoods->startTrans();
                $this->error("商品修改失败");
            }
        }else{
            $arr=$this->sellerGoods->where("id=".$id)->find();
            $data=$arr;
            if($arr['is_promote']=="1")    // 是否开启了促销
            {
                $data['promote_start_date']=date("m-d-Y",$arr['promote_start_date']);   // 促销起始时间
                $data['promote_end_date']=date("m-d-Y",$arr['promote_end_date']);   // 促销结束时间
            }
            $data['add_time']=date("Y-m-d",$arr['add_time']);
            $data['last_update']=date("Y-m-d",$arr['last_update']);
            /*
             * id , goods , url
             * */
            $brr=$this->sellerGoodsGallery->field(array('id,goods_id,url'))->where('goods_id='.$id)->select();
            $this->assign("gallery",$brr);
            $this->assign("data",$data);
            $this->display();
        }
    }

    /*
     * 商品的删除
     *$id为 商品ID
     * */
    function delGoods($id=''){

        //删除此上皮难度图集
        $arr=$this->sellerGoodsGallery->field("url")->where("goods_id=".$id)->select();

        foreach($arr as $r)
        {
            print_r($r['url']);
            $yanG2="../ddgc/Uploads{$r['url']}";
            if(file_exists($yanG2))
            {
                echo "文件存在";
                $yanG3=@unlink($yanG2);    // 删除文件夹中的文件
                if($yanG3==false)
                {
                    echo "商品没有从文件夹中删除";
                }else{
                    echo "商品成功删除";
                }
            }else{
                echo "文件不存在";
            }
        }
        $a1=$this->sellerGoodsGallery->where("goods_id=".$id)->delete(); //删除图集表中的此商品的数据

        if($a1)
        {
            $this->sellerGoodsGallery->commit();
        }else{
            $this->sellerGoodsGallery->rollback();
        }

        $a2=$this->sellerGoods->where("id=".$id)->delete();

        if($a2)
        {
            $this->sellerGoodsGallery->commit();
        }else{
            $this->sellerGoodsGallery->rollback();
        }

        $this->success("商品删除成功");

    }


    // 两种统计，1：微信支付 2：货到付款
    function myHrefOrder_b($cond="",$payType="")
    {
        $cond['pay_type']=$payType;
        $data['countOrderNum']=$this->orderInfo->where($cond)->count();
        $data['sumAmount']=$this->orderInfo->where($cond)->sum("goods_amount");
        $cond['pay_status']="2";   // 以下情况都是支付了的
        $data['alreadyCount']=$this->orderInfo->where($cond)->count();
        $data['alreadySumAmount']=$this->orderInfo->where($cond)->sum("goods_amount");
        return $data;
    }


    function myHrefOrder($condition="")
    {
        switch($condition)
        {
            case 1:
                $cond['order_status']="2";
                break;
            case 2:
                $cond['order_status']="0";
                break;
            case 3:
                $cond['pay_status']="2";
                break;
            case 4:
                $cond['pay_status']="0";
                break;
        }
        $cond['seller_id']=$this->sellerID;

        $statPayType0=$this->myHrefOrder_b($cond,0); // 第二个参数为0时,表示货到付款
        $statPayType1=$this->myHrefOrder_b($cond,1); // 第一个参数为1时，表示微信支付

        $yanG2=$this->orderInfo->where($cond)->order('id desc')->select();

        // 通过  order_id  得到 相关订单信息 ， 存入数组
        $orderList = array();
        foreach ($yanG2 as $key => $r){
            $yanG3 = D('Users')->field("nick")->where("id=" . $r['user_id'])->find();
            $orderList[$key]['id']=$r['id'];
            $orderList[$key]['username'] = $yanG3['nick'];
            $orderList[$key]['order_status_b']=$r['order_status']==2 ? "<font color='#006600' weight='bold'>交易成功</font>" : "<font color='#ff0000' weight='bold'>交易未成功</font>";
            $orderList[$key]['pay_status_b'] = $r['pay_status'] == 2 ? "<font color='#000066' weight='bold'>支付成功</font>" : "<font color='#ff6600' weight='bold'>未支付</font>";
            $orderList[$key]['phone'] = $r['mobile'];
            $orderList[$key]['name'] = $r['consignee'];
            $orderList[$key]['amount'] = $r['goods_amount'];
            if($r['pay_type']=="0")
            {
                $orderList[$key]['pay_type_b']="货到付款";
            }elseif($r['pay_type']=="1")
            {
                $orderList[$key]['pay_type_b']="微信支付";
            }elseif($r['pay_type']=="2")
            {
                $orderList[$key]['pay_type_b']="货到付款";
            }
            $orderList[$key]['add_time_b'] = date("Y-m-d H:i:s", $r['add_time']);
            $orderList[$key]['order_sn']=$r['order_sn'];
        }

        $this->assign("statPayType0",$statPayType0);
        $this->assign("statPayType1",$statPayType1);

        $this->assign("orderList",$orderList);
        $this->assign("sellerName",$this->seller);
        $isWap=self::check_wap();
        if($isWap===true)
        {
            $this->display("wap");
        }else{
            $this->display("order");
//            $this->display("order");
        }
    }

    function myOrder($condition="")
    {
        if($_POST)
        {
            if($condition=="1")
            {
                //$yanG2 = $this->sellerGoods->query("select id,order_sn,user_id,order_status,pay_status,pay_type,add_time from ddgc_order_info where pay_status={$_POST['pay_status']} AND id in(select order_id from ddgc_order_goods where goods_id in (select id from ddgc_goods where seller_id={$this->sellerID}))");
                $cond['pay_status']=$_POST['pay_status'];
                $cond['seller_id']=$this->sellerID;
                $yanG2 = $this->orderInfo->where($cond)->select();

                //统计
                $countOrderNum=$this->orderInfo->where($cond)->count();
                $sumAmount=$this->orderInfo->where($cond)->sum("goods_amount");
                $alreadyCount=$this->orderInfo->where("pay_status=2 AND seller_id={$this->sellerID}")->count();
                $alreadySumAmount=$this->orderInfo->where($cond)->sum("goods_amount");
                //统计END

                $this->assign("pay_status",$_POST['pay_status']);
            }elseif($condition=="2")
            {
                //$yanG2 = $this->sellerGoods->query("select id,order_sn,user_id,order_status,pay_status,pay_type,add_time from ddgc_order_info where pay_status={$_POST['pay_type']} AND id in(select order_id from ddgc_order_goods where goods_id in (select id from ddgc_goods where seller_id={$this->sellerID}))");
                $cond['pay_type']=$_POST['pay_type'];
                $cond['seller_id']=$this->sellerID;
                $yanG2=$this->orderInfo->where($cond)->select();

                //统计
                $countOrderNum=$this->orderInfo->where($cond)->count();
                $sumAmount=$this->orderInfo->where($cond)->sum("goods_amount");
                $alreadyCount=$this->orderInfo->where("pay_status=2 AND pay_type={$_POST['pay_type']} AND seller_id={$this->sellerID}")->count();
                $alreadySumAmount=$this->orderInfo->where("pay_status=2 AND pay_type={$_POST['pay_type']} AND seller_id={$this->sellerID}")->sum("goods_amount");
                //统计END

                $this->assign("pay_type",$_POST['pay_type']);
            }elseif($condition=="3")
            {
                $promote_start_date=$_POST['startTime'];
                $yanG1=explode("-",$promote_start_date);
                $yanGstart=mktime(0,0,0,$yanG1[0],$yanG1[1],$yanG1[2]);      // 得到促销开始的时间戳
                $promote_end_date=$_POST['endTime'];
                $yanG2=explode("-",$promote_end_date);
                $yanGend=mktime(0,0,0,$yanG2[0],$yanG2[1],$yanG2[2]);      // 得到促销结束的时间戳
                $yanG2=$this->orderInfo->where("add_time>{$yanGend} AND add_time<{$yanGstart} AND seller_id={$this->sellerID}")->select();

                //统计
                $countOrderNum=$this->orderInfo->where("add_time>{$yanGend} AND add_time<{$yanGstart} AND seller_id={$this->sellerID}")->count();
                $sumAmount=$this->orderInfo->where("add_time>{$yanGend} AND add_time<{$yanGstart} AND seller_id={$this->sellerID}")->sum("goods_amount");
                $alreadyCount=$this->orderInfo->where("pay_status=2 AND add_time>{$yanGend} AND add_time<{$yanGstart} AND seller_id={$this->sellerID}")->count();
                $alreadySumAmount=$this->orderInfo->where("pay_status=2 AND add_time>{$yanGend} AND add_time<{$yanGstart} AND seller_id={$this->sellerID}")->sum("goods_amount");
                //统计END

            }elseif($condition=="4")
            {
                //$yanG2 = $this->sellerGoods->query("select id,order_sn,user_id,order_status,pay_status,pay_type,add_time from ddgc_order_info where order_sn={$_POST['order_sn']} AND id in(select order_id from ddgc_order_goods where goods_id in (select id from ddgc_goods where seller_id={$this->sellerID}))");
                $cond['order_sn']=$_POST['order_sn'];
                $cond['seller_id']=$this->sellerID;
                $yanG2 = $this->orderInfo->where($cond)->select();

                //统计
                $countOrderNum=$this->orderInfo->where($cond)->count();
                $sumAmount=$this->orderInfo->where($cond)->sum("goods_amount");
                $alreadyCount=$this->orderInfo->where("pay_status=2 AND order_sn={$_POST['order_sn']} AND seller_id={$this->sellerID}")->count();
                $alreadySumAmount=$this->orderInfo->where("pay_status=2 AND order_sn={$_POST['order_sn']} AND seller_id={$this->sellerID}")->sum("goods_amount");
                //统计END

                $this->assign("order_sn",$_POST['order_sn']);
            }elseif($condition=="5")
            {
                //$yanG2 = $this->sellerGoods->query("select id,order_sn,user_id,order_status,pay_status,pay_type,add_time from ddgc_order_info where order_status={$_POST['order_status']} AND id in(select order_id from ddgc_order_goods where goods_id in (select id from ddgc_goods where seller_id={$this->sellerID}))");
                $cond['order_status']=$_POST['order_status'];
                $cond['seller_id']=$this->sellerID;
                $yanG2 = $this->orderInfo->where($cond)->select();
                //统计
                $countOrderNum=$this->orderInfo->where($cond)->count();
                $sumAmount=$this->orderInfo->where($cond)->sum("goods_amount");
                $alreadyCount=$this->orderInfo->where("pay_status=2 AND order_status={$_POST['order_status']} AND seller_id={$this->sellerID}")->count();
                $alreadySumAmount=$this->orderInfo->where("pay_status=2 AND order_status={$_POST['order_status']} AND seller_id={$this->sellerID}")->sum("goods_amount");
                //统计END

                $this->assign("order_status",$_POST['order_status']);
            }
        }else {
            //  通过  goods_id  得到商户的  order_id
            $yanG2 = $this->orderInfo->where("seller_id=".$this->sellerID)->select();
            $countOrderNum=$this->orderInfo->where("seller_id=".$this->sellerID)->count();
            $sumAmount=$this->orderInfo->where("seller_id=".$this->sellerID)->sum("goods_amount");
            $alreadyCount=$this->orderInfo->where("seller_id={$this->sellerID} AND pay_status=2")->count();
            $alreadySumAmount=$this->orderInfo->where("seller_id={$this->sellerID} AND pay_status=2")->sum("goods_amount");
        }
        // 通过  order_id  得到 相关订单信息 ， 存入数组
        $orderList = array();
        foreach ($yanG2 as $key => $r){
            $yanG3 = D('Users')->field("nick")->where("id=" . $r['user_id'])->find();
            $orderList[$key]['id']=$r['id'];
            $orderList[$key]['username'] = $yanG3['nick'];
            $orderList[$key]['order_status_b']=$r['order_status']==2 ? "交易成功" : "交易未成功";
            $orderList[$key]['pay_status_b'] = $r['pay_status'] == 2 ? "支付成功" : "未支付";
			$orderList[$key]['phone'] = $r['mobile'];
			$orderList[$key]['name'] = $r['consignee'];
			$orderList[$key]['amount'] = $r['goods_amount'];
            if($r['pay_type']=="0")
            {
                $orderList[$key]['pay_type_b']="货到付款";
            }elseif($r['pay_type']=="1")
            {
                $orderList[$key]['pay_type_b']="微信支付";
            }elseif($r['pay_type']=="2")
            {
                $orderList[$key]['pay_type_b']="货到付款";
            }
            $orderList[$key]['return_money_b'] = $r['return_money']==1?"<font color='#FF0000' weight='900'>已回款</font>":"未回款";
            $orderList[$key]['add_time_b'] = date("Y-m-d H:i:s", $r['add_time']);
            $orderList[$key]['order_sn']=$r['order_sn'];
        }

        $this->assign("sumAmount",$sumAmount);
        $this->assign("countOrderNum",$countOrderNum);
        $this->assign("alreadySumAmount",$alreadySumAmount);
        $this->assign("alreadyCount",$alreadyCount);

        $this->assign("orderList",$orderList);
        $this->assign("sellerName",$this->seller);
        $isWap=self::check_wap();
        if($isWap===true)
        {
            $this->display("wap");
        }else{
            $this->display("order");
//            $this->display("order");
        }
    }

    /*
     * $id 为商品ID
     *
     * 上传多图
     * */
    function upMoreImg($id='')
    {
        $upload = new \Think\Upload();
        $upload->maxSize = 3145728;
        $upload->exts = array('jpg','gif','png','jpeg');
        $upload->savePath='./seller/pic_goods/';      // 设置上传目录
        $upload->subName  = array('date','Ymd');
        $info = $upload->upload();
        if(!$info){
            $this->error($upload->getError());
        }else{
            foreach($info as $file)
            {
                //echo $file['savepath'].$file['savename'];
                $data['id']='';
                $data['goods_id']=$id;
                $yanG1=$file['savepath'].$file['savename'];
                $yanG2=explode(".",$yanG1);
                $data['url']=$yanG2[1].".".$yanG2[2];
                $a3=$this->sellerGoodsGallery->data($data)->add();
                if($a3)
                {
                    $this->sellerGoodsGallery->commit();
                }else{
                    $this->sellerGoodsGallery->rollback();
                }
            }
        }
        $this->redirect('Business/index');
    }

    /*
     * 单个文件的上传 $goods_sn
     * */
    function uploadOneImg($tran='')         //  %tran 将会得到两个值 thumb 或者 img
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->autoSub = false;
        $upload->replace = true;
        if($tran=='thumb')
        {
            $upload->savePath  = './thumb/'; // 设置附件上传目录
//            $upload->saveName  = $goods_sn;
            $info   =   $upload->uploadOne($_FILES['thumb']);
        }
        elseif($tran=='img')
        {
            $upload->savePath  = './seller/pic_goods/'; // 设置附件上传目录
//            $upload->saveName  = $goods_sn;
            $info   =   $upload->uploadOne($_FILES['img']);
        }
        else
        {
            echo "上传图片错误，可能后台代码的问题!!";
            exit;
        }

        // 上传单个文件

        if(!$info){// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功 获取上传文件信息
            //echo $info['savepath'].$info['savename'];
            return $info['savename'];
        }
    }

    /*
     * 删除图片
     * 单个图片的删除
     * $id 图片的唯一ID
     * $url 图片的路径
     * */
    function delOne($id)
    {
        $yanG1=$this->sellerGoodsGallery->field('url')->where('id='.$id)->find();
        //$yanG2="<img src=/thinkphp/Uploads{$yanG1['url']}>";
        $yanG2="../thinkphp/Uploads{$yanG1['url']}";
        if(file_exists($yanG2)){    // 判断文件是否存在
            $yanG3=@unlink($yanG2);    // 删除文件
            if($yanG3==false)
            {
                $this->error("删除失败");//删除失败
            }else{
                $yanG4=$this->sellerGoodsGallery->where("id=".$id)->delete();
                if($yanG4==true)
                {
                    $this->sellerGoodsGallery->commit();
                    $this->success("删除成功");
                }else{
                    $this->sellerGoodsGallery->rollback();
                    $this->error("数据库删除失败");
                }
            }
        }else{
            $a4=$this->sellerGoodsGallery->where("id=".$id)->delete();
            if(a4)
            {
                $this->sellerGoodsGallery->commit();
            }else{
                $this->sellerGoodsGallery->rollback();
            }
            $this->error("文件不存在,清理数据库中的残余");
        }
        exit;
    }

    function basicInfo()
    {
        if($_POST)
        {
            $data['address']=$_POST['address'];
            $data['linkman']=$_POST['linkman'];
            $data['tel']=$_POST['tel'];
            $a5=$this->sellerDB->where("id=".$this->sellerID)->save($data);
            if($a5)
            {
                $this->sellerDB->commit();
            }else{
                $this->sellerDB->rollback();
            }
        }
        $arr=$this->sellerDB->where("id=".$this->sellerID)->find();
        $this->assign("data",$arr);
        $this->display();
    }

    // 得到 订单的详细信息
    function orderInfo($id='')
    {
        $cond['id']=$id;
        $yanG1=$this->orderInfo->where($cond)->find();  // 得到相应的订单信息

        $yanG1['order_status_b'] = $yanG1['order_status']==2 ? "交易完成":"交易未完成";

        $yanG1['pay_status_b'] = $yanG1['pay_status'] == 2 ? "支付成功" : "未支付";
        if($yanG1['pay_type']=="0")
        {
            $yanG1['pay_type_b']="货到付款";
        }elseif($yanG1['pay_type']=="1")
        {
            $yanG1['pay_type_b']="微信支付";
        }
        if($yanG1['shipping_type']=="1")   // 门店自提
        {
            $sellerInfo=$this->sellerDB->where("id=".$yanG1['seller_id'])->find();;
            $yanG1['shipping_type_b']="门店自提(".$sellerInfo['nick']."门店地址".$sellerInfo['address'].")";
        }else{
            $yanG1['shipping_type_b']="送货上门";
        }
        $yanG1['add_time_b']=date("Y-m-d  H:i:s",$yanG1['add_time']);

        $yanG1['return_money_b']=$yanG1['return_money']==1?"<font color='#FF0000' weight='900'>已回款</font>":"未回款";

        $this->assign("data",$yanG1);

        $yanG2=$this->orderGoods->where("order_id=".$id)->select();
        foreach($yanG2 as $key=>$r)
        {
            $yanG3=$this->goods->field("id","name","thumb")->where("id=".$r['goods_id'])->find();
            $yanG2[$key]['goodsName']=$yanG3['name'];
            $yanG2[$key]['thumb']=$yanG3['thumb'];
        }
        $this->assign("yanG2",$yanG2);
        $this->display("orderInfo");
    }

    function updataOrderStatus($id='',$val='')
    {
        $data['order_status']=$val;
        $a6=$this->orderInfo->where("id=".$id)->save($data);
        if($a6)
        {
            $this->orderInfo->commit();
            $this->success("操作成功");
        }else{
            $this->orderInfo->rollback();
            $this->error("操作失败");
        }
    }
}